package com.kuang.web.admin;

import com.kuang.pojo.Tag;
import com.kuang.pojo.User;
import com.kuang.service.BlogTagService;
import com.kuang.service.TagService;
import com.kuang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class TagController {
    @Autowired
    private UserService userService;

    @Autowired
    private BlogTagService blogTagService;

    @Autowired
    private TagService tagService;

    @RequestMapping("/totag")
    public String totag(Model model) {
        List<Tag> tagList = tagService.selectAllTag();
//        System.out.println(tagList);
        model.addAttribute("taglist", tagList);
        return "admin/tag-mgr";

    }

    @RequestMapping("/addtag")
    @ResponseBody
    public String addtag(String name, Model model) {
        User user1 = userService.selectAdminUser(1);
        model.addAttribute("user1", user1);
        Tag tag = tagService.selectTagByName(name);
        if (tag != null) {
            return "error";
        } else {
            tagService.insertTag(name, new Date(), new Date());
            return "success";

        }
    }

    @RequestMapping("/deletetag")
    @ResponseBody
    public String deletetag(Integer tagid) {
        int i = tagService.deleteTagById(tagid);
        int i1 = blogTagService.updateBlogIdByTagId(tagid);
        if (i > 0 && i1 > 0) {
            return "success";

        } else {
            return "error";
        }
    }

    @RequestMapping("/modifytag")
    @ResponseBody
    public String modifytag(int tagid, String tagname) {
        System.out.println(tagid);
        System.out.println(tagname);
//        int id = Integer.parseInt(tagid);
        int i = tagService.updateTagById(tagid, tagname, new Date());
        if (i > 0) {
            return "success";
        } else {
            return "error";

        }
    }

    @RequestMapping("/totagpage")
    public String totagpage(Model model, @RequestParam(defaultValue = "1") Integer pageindex) {
        User user1 = userService.selectAdminUser(1);
        model.addAttribute("user1", user1);
        int pagesize = 5;  // 每页显示5个
        int counttag = tagService.countTag();
        int pageAll = counttag % pagesize == 0 ? counttag / pagesize : (counttag / pagesize) + 1;
        List<Tag> tagList = tagService.selectTagPage((pageindex - 1) * pagesize, pagesize);
        model.addAttribute("pageindex", pageindex);
        model.addAttribute("pageAll", pageAll);
        model.addAttribute("taglist", tagList);
        model.addAttribute("counttag", counttag);
        return "admin/tag-mgr";

    }
}